//
//  ComplainDetailController.m
//  protesteya
//
//  Created by Sebastian Bene on 9/23/13.
//  Copyright (c) 2013 Obligatorio Dispositivos Moviles. All rights reserved.
//

#import "ComplainDetailController.h"
#import "TwitterInvoker.h"
#import "ResponseParser.h"
#import <MapKit/MapKit.h>
#import "DejalActivityView.h"
#import "ComplainImageFullScreenController.h"
#import <QuartzCore/QuartzCore.h>

@interface ComplainDetailController ()

@property (strong, nonatomic) IBOutlet UILabel *textComplain;
@property (strong, nonatomic) IBOutlet MKMapView *mapComplain;
@property (strong, nonatomic) IBOutlet UIImageView *imageComplain;
@property (strong, nonatomic) IBOutlet UIImageView *imageLocationNotAvailable;
@property (strong, nonatomic) IBOutlet UIImageView *userImage;
@property (strong, nonatomic) IBOutlet UIImageView *imageNotAvailable;
@property (strong, nonatomic) IBOutlet UILabel *userName;
@property (strong, nonatomic) IBOutlet UILabel *createdDate;
@property (strong, nonatomic) IBOutlet UIImageView *imageFavorite;
@property (strong, nonatomic) IBOutlet UIImageView *imageRetweet;
@property (strong, nonatomic) IBOutlet UIView *generalView;
@property (strong, nonatomic) IBOutlet UIView *imageView;
@property (strong, nonatomic) IBOutlet UIView *mapView;

@end

@implementation ComplainDetailController

- (void)viewDidLoad
{
    [DejalActivityView activityViewForView:self.view withLabel:@"Cargando Protesta..."];
    
    [super viewDidLoad];
    tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageToFullScreen)];
    tap.delegate = self;
    [_imageComplain addGestureRecognizer:tap];
    _generalView.layer.cornerRadius = 10.0f;
    _generalView.layer.masksToBounds = YES;
    _imageView.layer.cornerRadius = 10.0f;
    _imageView.layer.masksToBounds = YES;
    _mapView.layer.cornerRadius = 10.0f;
    _mapView.layer.masksToBounds = YES;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    ResponseParser *parser = [[ResponseParser alloc] init];
    
    _tweetDetail = [parser ParseGetTweetResponse:self.tweet withImage:YES];
    
    if(_tweetDetail.responseType == TwitterResponseError)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:_tweetDetail.errorMessage delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    }
    else
    {
        _textComplain.text = _tweetDetail.text;
        
        if(_tweetDetail.image)
        {
            _imageComplain.image = _tweetDetail.image;
            _imageComplain.hidden = NO;
        }
        else
        {
            _imageNotAvailable.hidden = NO;
        }
        
        if(_tweetDetail.userImage)
        {
            _userImage.image = _tweetDetail.userImage;
            _userImage.hidden = NO;
        }
        
        _userName.text = _tweetDetail.userName;
        _createdDate.text = _tweetDetail.createdDate;
        
        _imageFavorite.hidden = !_tweetDetail.isFavorite;
        _imageRetweet.hidden = !_tweetDetail.isRetweeted;
        
        if(_tweetDetail.latitude && _tweetDetail.longitude)
        {
            self.mapComplain.hidden = NO;
            CLLocationCoordinate2D location;
            location.latitude = [_tweetDetail.latitude doubleValue];
            location.longitude = [_tweetDetail.longitude doubleValue];
            
            MKPointAnnotation *newAnnotation = [[MKPointAnnotation alloc] init];
            newAnnotation.coordinate = location;
            [self.mapComplain addAnnotation:newAnnotation];
            
            MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(location, 500, 500);
            [self.mapComplain setRegion:region animated:NO];
            [self.mapComplain selectAnnotation:newAnnotation animated:NO];
        }
        else
        {
            self.imageLocationNotAvailable.hidden = NO;
        }
    }
    
    [DejalActivityView removeView];
}

-(void) setDetail:(NSDictionary *) tweet
{
    self.tweet = tweet;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch;
{
    BOOL shouldReceiveTouch = YES;
    
    if (gestureRecognizer == tap) {
        shouldReceiveTouch = (touch.view == _imageComplain);
    }
    
    return shouldReceiveTouch;
}

-(void)imageToFullScreen{
    [self performSegueWithIdentifier:@"imageFullScreen" sender:self];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"imageFullScreen"])
    {
        [segue.destinationViewController setImageFullScreen:_imageComplain.image];
    }else{
        [segue.destinationViewController setDetail:self.tweet];
    }
}

-(void)getResponse:(NSDictionary *)response
{
    ResponseParser *parser = [[ResponseParser alloc] init];
    TwitterBaseResponse *tweetResponse = [parser ParseTwitterBaseResponse:response];
    
    if(tweetResponse.responseType == TwitterResponseError)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:tweetResponse.errorMessage delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:YES];
    }
    else
    {
        _imageFavorite.hidden = !_tweetDetail.isFavorite;
        _imageRetweet.hidden = !_tweetDetail.isRetweeted;
    }
    
    _invoker.tweeterInvokerDelegate = nil;
    [DejalBezelActivityView removeViewAnimated:YES];
}

- (IBAction)OpenActionsMenu:(id)sender {
    actionSheet = [[UIActionSheet alloc] initWithTitle:@"Seleccione Accion:"
                                        delegate:self
                               cancelButtonTitle:@"Cancelar"
                          destructiveButtonTitle:nil
                                     otherButtonTitles:@"Difundir", _tweetDetail.isFavorite ? @"Quitar de Favoritos" : @"Añadir a Favoritos", @"Ver Comentarios", nil];
    
    actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
	actionSheet.destructiveButtonIndex = 3;
	[actionSheet showFromToolbar:self.navigationController.toolbar];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if (buttonIndex == 0)
	{
        [self Retweet];
	}
	else if(buttonIndex == 1)
	{
		[self AddRemoveFavorite];
	}
    else if(buttonIndex == 2)
	{
		[self performSegueWithIdentifier:@"viewComments" sender:self];
	}
}

- (void)willPresentActionSheet:(UIActionSheet *)actSheet
{
    if(_tweetDetail.isRetweeted)
    {
        for (UIView *view in [actSheet subviews])
        {
            if ([view respondsToSelector:@selector(title)])
            {
                NSString* title = [view performSelector:@selector(title)];
                if ([title isEqualToString:@"Difundir"] && [view respondsToSelector:@selector(setEnabled:)])
                {
                    [view performSelector:@selector(setEnabled:) withObject:NO];
                }
            }
        }
    }
}

- (void)Retweet {
    [DejalBezelActivityView activityViewForView:self.view withLabel:@"Difundiendo Protesta..."];
    
    RetweetRequest *request = [[RetweetRequest alloc] init];
    request.tweetId = _tweetDetail.tweetId;
    
    _invoker = [[TwitterInvoker alloc] init];
    _invoker.tweeterInvokerDelegate = self;
    [_invoker Retweet:request];
    
    _tweetDetail.isRetweeted = YES;
    
}

- (void)AddRemoveFavorite {
    FavoriteRequest *request = [[FavoriteRequest alloc] init];
    request.tweetId = _tweetDetail.tweetId;
    
    _invoker = [[TwitterInvoker alloc] init];
    _invoker.tweeterInvokerDelegate = self;
    
    if(_tweetDetail.isFavorite)
    {
        [DejalBezelActivityView activityViewForView:self.view withLabel:@"Quitando Protesta de Favoritos..."];
        [_invoker RemoveFromFavorites:request];
    }
    else
    {
        [DejalBezelActivityView activityViewForView:self.view withLabel:@"Agregando Protesta a Favoritos..."];
        [_invoker AddToFavorites:request];
    }
    
    _tweetDetail.isFavorite = !_tweetDetail.isFavorite;
}

@end
